﻿#include "CList.h"
#include <string.h>
#include <stdlib.h>

typedef struct _CLIST_NODE {
	struct _CLIST_NODE* pre;
	struct _CLIST_NODE* next;
} CLIST_NODE;

int clist_insert(struct _clist_* thes, void* e) {
    char* _acd_pc = (char*)malloc(sizeof(CLIST_NODE) + thes->item_size);
    CLIST_NODE* it = (CLIST_NODE*)_acd_pc;
    CLIST_NODE* ph = (CLIST_NODE*)thes->ptr;
    CLIST_NODE* ptail = ph->pre;
    memcpy(_acd_pc + sizeof(CLIST_NODE), e, thes->item_size) ;

	ptail->next = it;
	it->next = ph;
	it->pre = ptail;
	ph->pre = it;
	thes->cnt++;
	return 0;
}

//int clist_erase(struct _clist_* thes, CListIterator* it) {
//    CLIST_NODE* ph = (CLIST_NODE*) thes->ptr;
//    CLIST_NODE* looper = ph->next;
//
//    if(ph == it->ptr) return -1;
//    while ( ph != looper ) {
//        if (it->ptr != looper) {
//        	looper = looper->next;
//        	continue;
//        }
//    	looper->next->pre = looper->pre;
//    	looper->pre->next = looper->next;
//        free(looper);
//		return 0;
//    }
//	return -2;
//}

int clist_erase(struct _clist_* thes, CListIterator* it) {
	CLIST_NODE* e = (CLIST_NODE*)it->ptr;
	if (thes->ptr == it->ptr) return -1;
	e->next->pre = e->pre;
	e->pre->next = e->next;
	it->ptr = e->pre;
	free(e);
	thes->cnt--;
	return 0;
}

void* clist_begin(struct _clist_* thes) {
	return ((CLIST_NODE*)thes->ptr)->next;
}

void* clist_end(struct _clist_* thes) {
	return thes->ptr;
}

int clist_release(struct _clist_* thes) {
	CLIST_NODE* ph = thes->ptr;
	CLIST_NODE* pIt = ph->next;

	while(ph != pIt) {
		CLIST_NODE* pTmp = pIt->next;
		free(pIt);
		pIt = pTmp;
	}
	free(ph);
	thes->ptr = 0;
	thes->cnt = 0;
	return 0;
}

int construct_clist(CList* thes, int item_size) {
	CLIST_NODE* ph = (CLIST_NODE*)malloc(sizeof(CLIST_NODE));
	ph->next = ph;
	ph->pre = ph;
	thes->ptr = ph;
	thes->item_size = item_size;
	thes->cnt = 0;

	thes->insert = clist_insert;
	thes->erase = clist_erase;
	thes->begin = clist_begin;
	thes->end = clist_end;
	thes->release = clist_release;
	return 0;
}

void* clist_iterator_next(struct _clist_itorator* thes) {
	thes->ptr = ((CLIST_NODE*)thes->ptr)->next;
	return thes->ptr;
}

int construct_clist_iterator(CListIterator* thes) {
	thes->ptr = 0;
	thes->next = clist_iterator_next;
	return 0;
}







